<template>
  <div class="navbar-management">
    <div class="page-header">
      <h1>顶部栏管理</h1>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新建配置
      </el-button>
    </div>

    <!-- 配置列表 -->
    <el-card>
      <div v-if="configs.length === 0" class="empty-state">
        <el-empty description="暂无配置">
          <el-button type="primary" @click="showCreateDialog">创建第一个配置</el-button>
        </el-empty>
      </div>
      
      <div v-else>
        <el-table :data="configs" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="Logo">
            <template #default="scope">
              <img
                v-if="scope.row.logo"
                :src="scope.row.logo"
                class="logo-preview"
                alt="Logo"
              />
              <span v-else class="no-logo">未设置</span>
            </template>
          </el-table-column>
          <el-table-column label="菜单项数量">
            <template #default="scope">
              {{ scope.row.items?.length || 0 }} 项
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.isActive ? 'success' : 'info'">
                {{ scope.row.isActive ? '激活' : '未激活' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间">
            <template #default="scope">
              {{ formatTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="editConfig(scope.row)">编辑</el-button>
              <el-button
                size="small"
                :type="scope.row.isActive ? 'warning' : 'success'"
                @click="toggleActive(scope.row)"
              >
                {{ scope.row.isActive ? '停用' : '激活' }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteConfig(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 配置编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑配置' : '新建配置'"
      width="800px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="Logo" prop="logo">
          <div class="logo-upload">
            <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="uploadLogo"
              accept="image/*"
            >
              <img v-if="form.logo" :src="form.logo" class="logo-image" />
              <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">
              <p>点击上传Logo</p>
              <p class="tip-text">支持 JPG、PNG 格式，建议尺寸 200x60px</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="菜单项">
          <div class="menu-items">
            <div
              v-for="(item, index) in form.items"
              :key="index"
              class="menu-item"
            >
              <el-card>
                <div class="item-header">
                  <span>菜单项 {{ index + 1 }}</span>
                  <el-button
                    size="small"
                    type="danger"
                    text
                    @click="removeItem(index)"
                  >
                    删除
                  </el-button>
                </div>
                
                <!-- 第一行：短输入框（标识符、链接） -->
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="标识符" :prop="`items.${index}.key`">
                      <el-input v-model="item.key" placeholder="如：home" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="链接" :prop="`items.${index}.link`">
                      <el-input v-model="item.link" placeholder="如：/" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <!-- 第二行：排序和是否显示 -->
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="排序" :prop="`items.${index}.sortOrder`">
                      <el-input-number v-model="item.sortOrder" :min="0" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否显示">
                      <el-switch v-model="item.isVisible" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <!-- 第三行：英文标题（单独一行） -->
                <el-row :gutter="16">
                  <el-col :span="24">
                    <el-form-item label="英文标题" :prop="`items.${index}.titleEn`">
                      <el-input v-model="item.titleEn" placeholder="English Title" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <!-- 第四行：西班牙语标题（单独一行） -->
                <el-row :gutter="16">
                  <el-col :span="24">
                    <el-form-item label="西班牙语标题" :prop="`items.${index}.titleEs`">
                      <el-input v-model="item.titleEs" placeholder="Título en español" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <!-- 第五行：日文标题（单独一行） -->
                <el-row :gutter="16">
                  <el-col :span="24">
                    <el-form-item label="日文标题" :prop="`items.${index}.titleJa`">
                      <el-input v-model="item.titleJa" placeholder="日本語タイトル" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </div>
            
            <el-button @click="addItem" type="dashed" style="width: 100%">
              <el-icon><Plus /></el-icon>
              添加菜单项
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="saveConfig">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { request } from '../../utils/request'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadRequestOptions } from 'element-plus'

interface NavbarItem {
  id?: number
  key: string
  titleEn: string
  titleEs: string
  titleJa: string
  link: string
  sortOrder: number
  isVisible: boolean
}

interface NavbarConfig {
  id?: number
  logo?: string
  isActive: boolean
  createdAt?: string
  items: NavbarItem[]
}

const configs = ref<NavbarConfig[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()

const form = reactive<NavbarConfig>({
  logo: '',
  isActive: true,
  items: []
})

const rules: FormRules = {
  'items.*.key': [
    { required: true, message: '请输入标识符', trigger: 'blur' }
  ],
  'items.*.titleEn': [
    { required: true, message: '请输入英文标题', trigger: 'blur' }
  ],
  'items.*.titleEs': [
    { required: true, message: '请输入西班牙语标题', trigger: 'blur' }
  ],
  'items.*.titleJa': [
    { required: true, message: '请输入日文标题', trigger: 'blur' }
  ],
  'items.*.link': [
    { required: true, message: '请输入链接', trigger: 'blur' }
  ]
}

const getConfigs = async () => {
  try {
    const response = await request.get('/navbar/config')
    if (response.success) {
      configs.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取配置列表失败')
  }
}

const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

const editConfig = (config: NavbarConfig) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(form, {
    ...config,
    items: config.items.map(item => ({ ...item }))
  })
}

const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    logo: '',
    isActive: true,
    items: []
  })
  formRef.value?.clearValidate()
}

const addItem = () => {
  form.items.push({
    key: '',
    titleEn: '',
    titleEs: '',
    titleJa: '',
    link: '',
    sortOrder: form.items.length,
    isVisible: true
  })
}

const removeItem = (index: number) => {
  form.items.splice(index, 1)
  // 重新排序
  form.items.forEach((item, idx) => {
    item.sortOrder = idx
  })
}

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const uploadLogo = async (options: UploadRequestOptions) => {
  const formData = new FormData()
  formData.append('file', options.file)

  try {
    const response = await request.post('/navbar/upload/logo', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.success) {
      form.logo = response.data.url
      ElMessage.success('Logo上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败')
  }
}

const saveConfig = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        let response
        if (isEdit.value) {
          response = await request.put(`/navbar/config/${form.id}`, {
            logo: form.logo,
            isActive: form.isActive
          })
          // 批量更新菜单项
          if (response.success) {
            await request.put('/navbar/items/batch', {
              configId: form.id,
              items: form.items
            })
          }
        } else {
          response = await request.post('/navbar/config', {
            logo: form.logo,
            items: form.items
          })
        }

        if (response.success) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          getConfigs()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }
  })
}

const toggleActive = async (config: NavbarConfig) => {
  try {
    const response = await request.put(`/navbar/config/${config.id}`, {
      isActive: !config.isActive
    })

    if (response.success) {
      ElMessage.success(config.isActive ? '已停用' : '已激活')
      getConfigs()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteConfig = async (config: NavbarConfig) => {
  try {
    await ElMessageBox.confirm('确定要删除这个配置吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await request.delete(`/navbar/config/${config.id}`)
    if (response.success) {
      ElMessage.success('删除成功')
      getConfigs()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  getConfigs()
})
</script>

<style scoped>
.navbar-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.logo-preview {
  width: 60px;
  height: 30px;
  object-fit: contain;
}

.no-logo {
  color: #909399;
  font-style: italic;
}

.logo-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logo-image {
  width: 100px;
  height: 60px;
  object-fit: contain;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 10px;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.logo-uploader-icon:hover {
  border-color: #409eff;
}

.upload-tip {
  flex: 1;
}

.upload-tip p {
  margin: 0 0 5px 0;
}

.tip-text {
  color: #909399;
  font-size: 12px;
}

.menu-items {
  width: 100%;
}

.menu-item {
  margin-bottom: 20px;
}

.menu-item :deep(.el-card__body) {
  padding: 20px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-weight: bold;
  color: #303133;
}

/* 优化表单项间距 */
.menu-item :deep(.el-form-item) {
  margin-bottom: 16px;
}

.menu-item :deep(.el-row:last-child .el-form-item) {
  margin-bottom: 0;
}

/* 优化输入框样式 */
.menu-item :deep(.el-input-number) {
  width: 100%;
}

.menu-item :deep(.el-switch) {
  margin-top: 4px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .menu-item .el-row .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .menu-item .el-row .el-col:not(:first-child) {
    margin-top: 16px;
  }
}
</style>